/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import { insertCSS } from '@base/utils';
import { debounce } from 'lodash';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { iframe } from '@base/config';

export interface IframeConfig {
  routesMap: { [key: string]: string };
  styles?: string;
  stylesPosition?: 'body' | 'head';
}

/**
 * @descriptions iframe配置项
 */
const { routesMap, styles, stylesPosition } = iframe;

/**
 * @descriptions iframe高度变化监听处理
 */
export function useIframeHeight(
  iframeRef: React.MutableRefObject<any>,
): [number, () => Document | null] {
  const [height, setHeight] = useState(0);
  const actionRef = useRef<{
    observer?: MutationObserver;
    iframeDoc?: Document;
    timer?: NodeJS.Timeout;
    height: number;
  }>({ height: 0 });

  // 防抖方式触发更新高度
  const triggerSetHeight = useCallback(
    debounce(
      () => {
        const { iframeDoc } = actionRef.current;
        if (iframeDoc) {
          const { scrollHeight } = iframeDoc.body;
          if (actionRef.current.height !== scrollHeight) {
            setHeight(scrollHeight);
          }
          actionRef.current.height = scrollHeight;
        }
      },
      300,
      { leading: false, trailing: true },
    ),
    [],
  );

  // 点击后修复高度
  const fixHeightByClick = () => triggerSetHeight();

  // 触发监听
  const triggerObserver = () => {
    try {
      if (!iframeRef.current) return null;
      const iframeWin = iframeRef.current.contentWindow || iframeRef.current.contentDocument;
      const iframeDoc = iframeWin.document;
      const MutationObserver =
        window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
      // iframe的body
      const target = iframeDoc.body;
      // 监听
      const observer = new MutationObserver(triggerSetHeight);
      observer.observe(target, {
        subtree: true,
        childList: true,
      });
      actionRef.current.observer = observer;
      actionRef.current.iframeDoc = iframeDoc;
      triggerSetHeight();
      iframeDoc.addEventListener('click', fixHeightByClick);
      return iframeDoc;
    } catch (error) {
      return null;
    }
  };

  useEffect(() => {
    return () => {
      const { observer, iframeDoc, timer } = actionRef.current;
      observer?.disconnect();
      iframeDoc?.removeEventListener('click', fixHeightByClick);
      clearTimeout(timer);
    };
  }, []);
  return [height, triggerObserver];
}

export function getOldRoute(pathname: string): string {
  const oldRoute = routesMap[`${pathname}`.replace(/^\/f\//, '')] || '';
  return oldRoute;
}

/**
 * @descriptions 兼容老页面样式
 */
export function fixStyles(iframeDoc: Document | null) {
  if (!iframeDoc || !styles) return;
  // 注入样式
  insertCSS(styles, iframeDoc, stylesPosition);
}
